<template>
  <!--头部-->
  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入标签关键词"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>


  <van-divider content-position="left">已选标签</van-divider>
  <!--已选标签内容-->
  <div v-if="tags.length === 0 ">请选择标签</div>
  <!--间距-->
  <van-space wrap>
    <van-tag v-for="tag in tags" :show=true closeable size="small" type="primary" @close="close(tag)">
      {{ tag }}
    </van-tag>
  </van-space>

  <van-divider content-position="left">选择标签</van-divider>
  <!--选择标签内容-->
  <van-tree-select
      v-model:active-id="tags"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />
  <div style="padding: 20px">
    <van-button block type="primary" @click="searchUser"> 根据已选标签搜索用户</van-button>
  </div>
</template>

<script setup>
import {ref} from "vue";
import {useRouter} from "vue-router";

const router = useRouter();

// 搜索文本
const searchText = ref("");

const originTagList = [
  {
    text: '性别',
    children: [
      {text: '男', id: '男'},
      {text: '女', id: '女'}
    ],
  },
  {
    text: '年级',
    children: [
      {text: '大一', id: '大一'},
      {text: '大二', id: '大二'},
      {text: '大三', id: '大三'},
      {text: '大四131231231', id: '大四131231231'},
      {text: '研一', id: '研一33333'},
      {text: '研二', id: '研二2222222'},
    ],
  },
];

let tagList = ref(originTagList);

/**
 * 搜索过滤
 */
const onSearch = () => {
  tagList.value = originTagList.map(parentTag => {
    const tempParentTag = {...parentTag};
    tempParentTag.children = parentTag.children.filter(item => item.text.includes(searchText.value));
    return tempParentTag;
  });
};

// 取消
const onCancel = () => {
  searchText.value = "";
  tagList.value = originTagList;
}

// 选择标签内容
const tags = ref([]);
const activeIndex = ref(0);


// 移除标签
const close = (id) => {
  tags.value = tags.value.filter(item => item !== id);
};


/**
 * 跳转到搜索用户结果页
 */
const searchUser = () => {

  router.push({
    path: '/user/list',
    query: {
      tags: tags.value
    }
  });
}


</script>

<style scoped>

</style>